import Vue from 'vue';

// 更新视图
Vue.prototype.vueSet = function (obj, path, newVal, oldVal) {
  if ((!!oldVal && oldVal !== 0) && newVal === oldVal) {
    console.log('数据无变化');
    return false;
  } // 数据没有发生变化不处理
  path = path.split('.'); // 读取路径
  let p = path.pop(); // 目标路径
  obj = this.getValueByPath(obj, path); // 获取要修改的数据
  Vue.set(obj, p, newVal); // 更新视图
  return true;
};

/** 根据路径在object中取值
 *  @param Object obj: 原始值
 *  @param string|array path: p1.p2|p1[p2]|['p1', 'p2']
 * */
Vue.prototype.getValueByPath = function (obj, path) {
  if (typeof obj === 'object') {
    if (typeof path === 'string') {
      path = path.replace(/\[(\w+)\]/g, '.$1');
      path = path.replace(/^\./, '');
      return path.split('.').reduce((pre, cur) => {
        return pre[cur];
      }, obj);
    } else if (Array.isArray(path)) {
      return path.reduce((pre, cur) => {
        return pre[cur];
      }, obj);
    } else {
      console.warn('路径不合法');
    }
  } else {
    console.warn('数据源不是一个对象');
  }
  return '';
};

/**
 * JSON处理
 * */
/*json格式化*/
export const formatJson = (json, options = {}) => {
  var reg = null,
    formatted = '',
    pad = 0,
    PADDING = '    ';
  options.newlineAfterColonIfBeforeBraceOrBracket = options.newlineAfterColonIfBeforeBraceOrBracket === true;
  options.spaceAfterColon = options.spaceAfterColon === false;
  if (typeof json !== 'string') {
    json = JSON.stringify(json);
  } else {
    json = JSON.parse(json);
    json = JSON.stringify(json);
  }
  reg = /([\{\}])/g;
  json = json.replace(reg, '\r\n$1\r\n');
  reg = /([\[\]])/g;
  json = json.replace(reg, '\r\n$1\r\n');
  reg = /(\,)/g;
  json = json.replace(reg, '$1\r\n');
  reg = /(\r\n\r\n)/g;
  json = json.replace(reg, '\r\n');
  reg = /\r\n\,/g;
  json = json.replace(reg, ',');
  if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
    reg = /\:\r\n\{/g;
    json = json.replace(reg, ':{');
    reg = /\:\r\n\[/g;
    json = json.replace(reg, ':[');
  }
  if (options.spaceAfterColon) {
    reg = /\:/g;
    json = json.replace(reg, ':');
  }
  (json.split('\r\n')).forEach(function (node, index) {
      var i = 0,
        indent = 0,
        padding = '';

      if (node.match(/\{$/) || node.match(/\[$/)) {
        indent = 1;
      } else if (node.match(/\}/) || node.match(/\]/)) {
        if (pad !== 0) {
          pad -= 1;
        }
      } else {
        indent = 0;
      }

      for (i = 0; i < pad; i++) {
        padding += PADDING;
      }

      formatted += padding + node + '\r\n';
      pad += indent;
    }
  );
  return formatted;
};

/*JSON<=>Object 支持function*/
let JSON_SERIALIZE_FIX = {
  PREFIX: "[[JSON_FUN_PREFIX_",
  SUFFIX: "_JSON_FUN_SUFFIX]]"
};
export const ObjecttoJSON = (obj) => {
  let sobj = JSON.stringify(obj, function (key, value) {
    if (typeof value === 'function') {
      return JSON_SERIALIZE_FIX.PREFIX + value.toString() + JSON_SERIALIZE_FIX.SUFFIX;
    }
    return value;
  });
  return sobj;
};
export const JSONtoObject = (json) => {
  return JSON.parse(json, function (key, value) {
    if (typeof value === 'string' &&
      value.indexOf(JSON_SERIALIZE_FIX.SUFFIX) > 0 && value.indexOf(JSON_SERIALIZE_FIX.PREFIX) == 0) {
      return eval("(" + value.replace(JSON_SERIALIZE_FIX.PREFIX, "").replace(JSON_SERIALIZE_FIX.SUFFIX, "") + ")");
    }
    return value;
  }) || {};
};


/****************************** 日期 ***********************************/

/**************************js扩展（暂时写这里）********************/
/*格式化日期*/
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}


/*计算距离当日时间*/
export const DateDiff = (sDate1) => {    //sDate1和sDate2是2002-12-18格式

  var now, oDate1, result

  oDate1 = new Date(sDate1);
  now = new Date()

  if (now.getFullYear() - oDate1.getFullYear() != 0) {
    result = Math.abs(now.getFullYear() - oDate1.getFullYear()) + '年'
  } else if (now.getMonth() - oDate1.getMonth() != 0) {
    result = Math.abs(now.getMonth() - oDate1.getMonth()) + '个月'
  } else if (now.getDate() - oDate1.getDate() != 0) {
    result = Math.abs(now.getDate() - oDate1.getDate()) + '天'
  } else if (now.getHours() - oDate1.getHours() != 0) {
    result = Math.abs(now.getHours() - oDate1.getHours()) + '小时'
  } else {
    result = Math.abs(now.getMinutes() - oDate1.getMinutes()) + '分钟'
  }

  return result
}
//计算某两个日期
export const DateDiff2 = (sDate1, sDate2) => {    //sDate1和sDate2是2002-12-18格式

  var oDate1, oDate2, result

  oDate1 = new Date(sDate1);
  oDate2 = new Date(sDate2)

  if (oDate2.getFullYear() - oDate1.getFullYear() != 0) {
    result = Math.abs(oDate2.getFullYear() - oDate1.getFullYear()) + '年'
  } else if (oDate2.getMonth() - oDate1.getMonth() != 0) {
    result = Math.abs(oDate2.getMonth() - oDate1.getMonth()) + '个月'
  } else if (oDate2.getDate() - oDate1.getDate() != 0) {
    result = Math.abs(oDate2.getDate() - oDate1.getDate()) + '天'
  } else if (oDate2.getHours() - oDate1.getHours() != 0) {
    result = Math.abs(oDate2.getHours() - oDate1.getHours()) + '小时'
  } else {
    result = Math.abs(oDate2.getMinutes() - oDate1.getMinutes()) + '分钟'
  }

  return result
}

/**
 * 计算某两个日期(精确到毫秒)
 * @param sign 分割符号
 * @param isEn 英文/中文后缀
 */
export const DateDiff3 = (start, end, sign, isEn) => {    //sDate1和sDate2是2002-12-18格式
  sign = sign || '';
  if (start && end) {
  } else {
    return '--'
  }

  var oDate1, oDate2, diff, result

  oDate1 = new Date(start);
  oDate2 = new Date(end);
  diff = Math.abs(oDate1 - oDate2)

  if (diff < 1000) {
    result = diff + sign + (isEn ? 'ms' : '毫秒')
  } else if (diff < 60000) {
    result = Math.round(diff / 1000) + sign + (isEn ? 's' : '秒')
  } else if (diff < 3600000) {
    result = Math.round(diff / 60000) + sign + (isEn ? 'm' : '分')
  } else if (diff < 86400000) {
    result = Math.round(diff / 3600000) + sign + (isEn ? 'h' : '小时')
  } else if (diff < 604800000) {
    result = Math.round(diff / 86400000) + sign + (isEn ? 'day' : '天')
  } else if (diff < 2505600000) {
    result = Math.round(diff / 604800000) + sign + (isEn ? 'week' : '周')
  } else if (diff < 31536000000) {
    result = Math.round(diff / 2505600000) + sign + (isEn ? 'month' : '月')
  } else {
    result = Math.round(diff / 31536000000) + sign + (isEn ? 'year' : '年')
  }
  return result
}

/**
 * 计算某两个日期(精确到毫秒)
 * 返回xx时xx分xx秒
 * */
export const DateDiff4 = (start, end, sign, isEn) => {    //sDate1和sDate2是2002-12-18格式
  sign = sign || '';
  if (start && end) {
  } else {
    return '--'
  }

  var oDate1, oDate2, diff, result

  oDate1 = new Date(start);
  oDate2 = new Date(end);
  diff = Math.abs(oDate1 - oDate2)

  result = '';

  if (diff >= 3600000) {
    result += parseInt(diff / 3600000) + '时';
    diff = diff % 3600000;
  }
  if (diff >= 60000) {
    result += parseInt(diff / 60000) + '分';
    diff = diff % 60000;
  }
  if (diff >= 1000) {
    result += parseInt(diff / 1000) + '秒';

  }

  return result
}

/* 字符串 */
//去除以’key‘开头的字符
export const trim = (str, key) => {
  let start = 0;
  let end = str.length;
  for (let i = 0; i < end; i++) {
    if (str[i] === key) {
      ++start;
      continue;
    } else {
      break
    }
  }
  for (let i = end - 1; i >= 0; i--) {
    if (str[i] === key) {
      --end;
      continue;
    } else {
      break
    }
  }
  str = end > start ? str.substring(start, end) : '';
  return str;
};
export const trim_left = (str, key) => {
  let start = 0;
  let end = str.length;
  for (let i = 0; i < end; i++) {
    if (str[i] === key) {
      ++start;
      continue;
    } else {
      break
    }
  }
  str = end > start ? str.substring(start, end) : '';
  return str;
};
export const trim_right = (str, key) => {
  let start = 0;
  let end = str.length;
  for (let i = end - 1; i >= 0; i--) {
    if (str[i] === key) {
      --end;
      continue;
    } else {
      break
    }
  }
  str = end > start ? str.substring(start, end) : '';
  return str;
};

/*数值单位转换*/
export const sizeFormat = (limit) => {
  let size = "";
  if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
    size = limit.toFixed(2) + "B";
  } else if (limit < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
    size = (limit / 1024).toFixed(2) + "KB";
  } else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + "MB";
  } else { //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  }

  var sizestr = size + "";
  var len = sizestr.indexOf("\.");
  var dec = sizestr.substr(len + 1, 2);
  if (dec == "00") {//当小数点后为00时 去掉小数部分
    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
  }
  return sizestr;
}

/*计算所占百分比（不带单位）*/
export const getPercent = (num, total) => {
  num = parseFloat(num);
  total = parseFloat(total);
  if (isNaN(num) || isNaN(total)) {
    return "-";
  }
  return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00);
}






